<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Courier New:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="npm," />





  <link rel="alternate" href="/atom.xml" title="Never_yu's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon/favicon.ico?v=5.0.1" />






<meta property="og:type" content="article">
<meta property="og:title" content="npm 全面介绍">
<meta property="og:url" content="https://neveryu.github.io/2017/04/10/npm/index.html">
<meta property="og:site_name" content="Never_yu's Blog">
<meta property="og:updated_time" content="2018-09-20T08:25:25.463Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="npm 全面介绍">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"hide"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: undefined,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://neveryu.github.io/2017/04/10/npm/"/>


<!-- 网页加载条 -->
<script src="/js/src/pace.min.js"></script>
  <title> npm 全面介绍 | Never_yu's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Never_yu's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">认真的人才有资格开玩笑</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-guestbook">
          <a href="/guestbook" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-commenting"></i> <br />
            
            留言
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-example">
          <a href="/example" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            示例
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
      
      
        <li class="menu-item"> <a title="把这个链接拖到你的工具栏中,任何网页都可以High" href='javascript:(
/*
 * Copyright (C) 2016 Never_yu (Neveryu.github.io) <React.dong.yu@gmail.com>
 * Sina Weibo (http://weibo.com/Neveryu)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function go() {

var songs = [
  "http://dl.stream.qqmusic.qq.com/C400001Qu4I30eVFYb.m4a?vkey=2127178E4405E7B8B268F20F05232485735CCF4FF8C1432F0360D2626D0B6C9564B5627C7AB481BBC685FEDB0946A50E97C66F0D1B008226&guid=7175649092&uin=0&fromtag=66",
  "",
  "",
  ""
];

function c() {
  var e = document.createElement("link");
  e.setAttribute("type", "text/css");
  e.setAttribute("rel", "stylesheet");
  e.setAttribute("href", f);
  e.setAttribute("class", l);
  document.body.appendChild(e)
}

function h() {
  var e = document.getElementsByClassName(l);
  for (var t = 0; t < e.length; t++) {
    document.body.removeChild(e[t])
  }
}

function p() {
  var e = document.createElement("div");
  e.setAttribute("class", a);
  document.body.appendChild(e);
  setTimeout(function() {
    document.body.removeChild(e)
  }, 100)
}

function d(e) {
  return {
    height : e.offsetHeight,
    width : e.offsetWidth
  }
}

function v(i) {
  var s = d(i);
  return s.height > e && s.height < n && s.width > t && s.width < r
}

function m(e) {
  var t = e;
  var n = 0;
  while (!!t) {
    n += t.offsetTop;
    t = t.offsetParent
  }
  return n
}

function g() {
  var e = document.documentElement;
  if (!!window.innerWidth) {
    return window.innerHeight
  } else if (e && !isNaN(e.clientHeight)) {
    return e.clientHeight
  }
  return 0
}

function y() {
  if (window.pageYOffset) {
    return window.pageYOffset
  }
  return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
}

function E(e) {
  var t = m(e);
  return t >= w && t <= b + w
}

function S() {
  var e = document.getElementById("audio_element_id");
  if(e != null){
    var index = parseInt(e.getAttribute("curSongIndex"));
    if(index > songs.length - 2) {
      index = 0;
    } else {
      index++;
    }
    e.setAttribute("curSongIndex", index);
    N();
  }

  e.src = i;
  e.play()
}

function x(e) {
  e.className += " " + s + " " + o
}

function T(e) {
  e.className += " " + s + " " + u[Math.floor(Math.random() * u.length)]
}

function N() {
  var e = document.getElementsByClassName(s);
  var t = new RegExp("\\b" + s + "\\b");
  for (var n = 0; n < e.length; ) {
    e[n].className = e[n].className.replace(t, "")
  }
}

function initAudioEle() {
  var e = document.getElementById("audio_element_id");
  if(e === null){
    e = document.createElement("audio");
    e.setAttribute("class", l);
    e.setAttribute("curSongIndex", 0);
    e.id = "audio_element_id";
    e.loop = false;
    e.bgcolor = 0;
    e.addEventListener("canplay", function() {
      setTimeout(function() {
        x(k)
      }, 500);
      setTimeout(function() {
        N();
        p();
        for (var e = 0; e < O.length; e++) {
          T(O[e])
        }
      }, 15500)
    }, true);
    e.addEventListener("ended", function() {
      N();
      h();
      go();
    }, true);
    e.innerHTML = " <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";
    document.body.appendChild(e);
  }
}

initAudioEle();
var e = 30;
var t = 30;
var n = 350;
var r = 350;

var curSongIndex = parseInt(document.getElementById("audio_element_id").getAttribute("curSongIndex"));
var i = songs[curSongIndex];

var s = "mw-harlem_shake_me";
var o = "im_first";
var u = ["im_drunk", "im_baked", "im_trippin", "im_blown"];
var a = "mw-strobe_light";

/* harlem-shake-style.css，替换成你的位置，也可以直接使用：//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css */
var f = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css";

var l = "mw_added_css";
var b = g();
var w = y();
var C = document.getElementsByTagName("*");
var k = null;
for (var L = 0; L < C.length; L++) {
  var A = C[L];
  if (v(A)) {
    if (E(A)) {
      k = A;
      break
    }
  }
}
if (A === null) {
  console.warn("Could not find a node of the right size. Please try a different page.");
  return
}
c();
S();
var O = [];
for (var L = 0; L < C.length; L++) {
  var A = C[L];
  if (v(A)) {
    O.push(A)
  }
}
})()'><i class="menu-item-icon fa fa-music fa-fw"></i> High一下</a></li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search fa-lg"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                npm 全面介绍
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2017-04-10T03:25:24+08:00" content="2017-04-10">
              2017-04-10
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/前端/" itemprop="url" rel="index">
                    <span itemprop="name">前端</span>
                  </a>
                </span>

                
                

              
            </span>
          

          

          

          
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">热度
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>℃
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <!-- <img src="http://i1.piimg.com/588926/30e7b49044d5cfc4.png" alt="summary-img-src-npm"> -->
<a id="more"></a>
<h1 id="什么是-NPM"><a href="#什么是-NPM" class="headerlink" title="什么是 NPM"></a>什么是 NPM</h1><p>npm 之于 Node.js ，就像 pip 之于 Python， gem 之于 Ruby， pear 之于 PHP 。</p>
<p>npm 是 Node.js 官方提供的包管理工具，他已经成了 Node.js 包的标准发布平台，用于 Node.js 包的发布、传播、依赖控制。npm 提供了命令行工具，使你可以方便地下载、安装、升级、删除包，也可以让你作为开发者发布并维护包。</p>
<h1 id="为什么要使用-NPM"><a href="#为什么要使用-NPM" class="headerlink" title="为什么要使用 NPM"></a>为什么要使用 NPM</h1><p>npm 是随同 Node.js 一起安装的包管理工具，能解决 Node.js 代码部署上的很多问题，常见的场景有以下几种：</p>
<ul>
<li>允许用户从 npm 服务器下载别人编写的第三方包到本地使用。</li>
<li>允许用户从 npm 服务器下载并安装别人编写的命令行程序到本地使用。</li>
<li>允许用户将自己编写的包或命令行程序上传到 npm 服务器供别人使用。</li>
</ul>
<p>npm 的背后，是基于 couchdb 的一个数据库，详细记录了每个包的信息，包括作者、版本、依赖、授权信息等。它的一个很重要的作用就是：将开发者从繁琐的包管理工作（版本、依赖等）中解放出来，更加专注于功能的开发。</p>
<h1 id="如何使用-NPM"><a href="#如何使用-NPM" class="headerlink" title="如何使用 NPM"></a>如何使用 NPM</h1><h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p>npm 不需要单独安装。在安装 Node 的时候，会连带一起安装 npm 。但是，Node 附带的 npm 可能不是最新版本，最后用下面的命令，更新到最新版本。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ sudo npm install npm@latest -g</span><br></pre></td></tr></table></figure></p>
<p>如果是 Window 系统使用以下命令即可：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install npm -g</span><br></pre></td></tr></table></figure></p>
<p>也就是使用 npm 安装自己。之所以可以这样，是因为 npm 本身与 Node 的其他模块没有区别。</p>
<p>然后，运行下面的命令，查看各种信息。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 查看 npm 命令列表</span></span><br><span class="line">$ npm <span class="built_in">help</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 查看各个命令的简单用法</span></span><br><span class="line">$ npm -l</span><br><span class="line"></span><br><span class="line"><span class="comment"># 查看 npm 的版本</span></span><br><span class="line">$ npm -v</span><br><span class="line"></span><br><span class="line"><span class="comment"># 查看 npm 的配置</span></span><br><span class="line">$ npm config list -l</span><br></pre></td></tr></table></figure></p>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><h3 id="npm-init"><a href="#npm-init" class="headerlink" title="npm init"></a>npm init</h3><p>npm init 用来初始化生成一个新的 package.json 文件。它会向用户提问一系列问题，如果你觉得不用修改默认配置，一路回车就可以了。<br>如果使用了 -f（代表force）、-y（代表yes），则跳过提问阶段，直接生成一个新的 package.json 文件。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm init -y</span><br></pre></td></tr></table></figure></p>
<h3 id="npm-set"><a href="#npm-set" class="headerlink" title="npm set"></a>npm set</h3><p>npm set 用来设置环境变量<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ npm <span class="built_in">set</span> init-author-name <span class="string">'Your name'</span></span><br><span class="line">$ npm <span class="built_in">set</span> init-author-email <span class="string">'Your email'</span></span><br><span class="line">$ npm <span class="built_in">set</span> init-author-url <span class="string">'http://yourdomain.com'</span></span><br><span class="line">$ npm <span class="built_in">set</span> init-license <span class="string">'MIT'</span></span><br></pre></td></tr></table></figure></p>
<p>上面命令等于为 npm init 设置了默认值，以后执行 npm init 的时候，package.json 的作者姓名、邮件、主页、许可证字段就会自动写入预设的值。这些信息会存放在用户主目录的 ~/.npmrc文件，使得用户不用每个项目都输入。如果某个项目有不同的设置，可以针对该项目运行 npm config。</p>
<h3 id="npm-info"><a href="#npm-info" class="headerlink" title="npm info"></a>npm info</h3><p>npm info 命令可以查看每个模块的具体信息。比如，查看 underscore 模块的信息。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm info underscore</span><br></pre></td></tr></table></figure></p>
<p>上面命令返回一个 JavaScript 对象，包含了 underscore 模块的详细信息。这个对象的每个成员，都可以直接从 info 命令查询。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ npm info underscore description</span><br><span class="line"></span><br><span class="line">$ npm info underscore homepage</span><br><span class="line"></span><br><span class="line">$ npm info underscore version</span><br></pre></td></tr></table></figure></p>
<h3 id="npm-search"><a href="#npm-search" class="headerlink" title="npm search"></a>npm search</h3><p>npm search 命令用于搜索 npm 仓库，它后面可以跟字符串，也可以跟正则表达式。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm search &lt;搜索词&gt;</span><br></pre></td></tr></table></figure></p>
<h3 id="npm-list"><a href="#npm-list" class="headerlink" title="npm list"></a>npm list</h3><p>npm list 命令以树形结构列出当前项目安装的所有模块，以及它们依赖的模块。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ npm list</span><br><span class="line"></span><br><span class="line"><span class="comment"># 加上 global 参数，会列出全局安装的模块</span></span><br><span class="line">$ npm list -global</span><br><span class="line"></span><br><span class="line"><span class="comment"># npm list 命令也可以列出单个模块</span></span><br><span class="line">$ npm list underscore</span><br></pre></td></tr></table></figure></p>
<h3 id="npm-install"><a href="#npm-install" class="headerlink" title="npm install"></a>npm install</h3><p>使用 npm 安装包的命令格式为：<br><code>npm [install/i] [package_name]</code></p>
<h4 id="本地模式和全局模式"><a href="#本地模式和全局模式" class="headerlink" title="本地模式和全局模式"></a>本地模式和全局模式</h4><p>npm 在默认情况下会从 <a href="http://npmjs.org" target="_blank" rel="external">http://npmjs.org</a> 搜索或下载包，将包安装到当前目录的 node_modules 子目录下。<br>如果你熟悉 Ruby 的 gem 或者 Python 的 pip，你会发现 npm 与它们的行为不同，gem 或 pip 总是以全局模式安装，使包可以供所有的程序使用，而 npm 默认会把包安装到当前目录下。这反映了 npm 不同的设计哲学。如果把包安装到全局，可以提供程序的重复利用程度，避免同样的内容的多分副本，但坏处是难以处理不同的版本依赖。如果把包安装到当前目录，或者说本地，则不会有不同程序依赖不同版本的包的冲突问题，同时还减轻了包作者的 API 兼容性压力，但缺陷则是同一个包可能会被安装许多次。</p>
<p>我们在使用 supervisor 的时候使用了 <code>npm install -g supervisor</code> 命令，就是以全局模式安装 supervisor 。</p>
<p>这里注意一点的就是，supervisor 必须安装到全局，如果你不安装到全局，错误命令会提示你安装到全局。如果不想安装到默认的全局，也可以自己修改全局路径到当前路径 <code>npm config set prefix &quot;路径&quot;</code> 安装完以后就可以用 supervisor 来启动服务了。<br>supervisor 可以帮助你实现这个功能，它会监视你对代码的驱动，并自动重启 Node.js 。</p>
<p>一般来说，全局安装只适用于工具模块，比如 eslint 和 gulp 。关于使用全局模式，多数时候并不是因为许多程序都有可能用到了它，为了减少多重副本而使用全局模式，而是因为<strong>本地模式不会注册 PATH 环境变量</strong>。<br>“本地安装”指的是将一个模块下载到当前项目的 node_modules 子目录，然后只有在项目目录之中，才能调用这个模块。</p>
<p>本地模式和全局模式的特点如下：</p>
<table>
<thead>
<tr>
<th style="text-align:center">模式</th>
<th style="text-align:center">可通过 require 使用</th>
<th style="text-align:center">注册 PATH</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">本地模式</td>
<td style="text-align:center">是</td>
<td style="text-align:center">否</td>
</tr>
<tr>
<td style="text-align:center">全局模式</td>
<td style="text-align:center">否</td>
<td style="text-align:center">是</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 本地安装</span></span><br><span class="line">$ npm install &lt;package name&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 全局安装</span></span><br><span class="line">$ sudo npm install -global &lt;package name&gt;</span><br><span class="line">$ sudo npm install -g &lt;package name&gt;</span><br></pre></td></tr></table></figure>
<p>npm install 也支持直接输入 Github 代码库地址。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ npm install git://github.com/package/path.git</span><br><span class="line">$ npm install git://github.com/package/path.git<span class="comment">#0.1.0</span></span><br></pre></td></tr></table></figure></p>
<p>安装之前，npm install 会先检查，node_modules 目录之中是否已经存在指定模块。如果存在，就不再重新安装了，即使远程仓库已经有了一个新版本，也是如此。</p>
<p>如果你希望，一个模块不管是否安装过， npm 都要强制重新安装，可以使用 -f 或 –force 参数。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install &lt;packageName&gt; --force</span><br></pre></td></tr></table></figure></p>
<h4 id="安装不同版本"><a href="#安装不同版本" class="headerlink" title="安装不同版本"></a>安装不同版本</h4><p>install 命令总是安装模块的最新版本，如果要安装模块的特定版本，可以在模块名后面加上 @ 和版本号。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ npm install sax@latest</span><br><span class="line">$ npm install sax@0.1.1</span><br><span class="line">$ npm install sax@<span class="string">"&gt;=0.1.0 &lt;0.2.0"</span></span><br></pre></td></tr></table></figure></p>
<p>install 命令可以使用不同参数，指定所安装的模块属于哪一种性质的依赖关系，即出现在 packages.json 文件的哪一项中。</p>
<blockquote>
<p>–save：模块名将被添加到 dependencies，可以简化为参数-S。<br>–save-dev：模块名将被添加到 devDependencies，可以简化为参数-D。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ npm install sax --save</span><br><span class="line">$ npm install node-tap --save-dev</span><br><span class="line"><span class="comment"># 或者</span></span><br><span class="line">$ npm install sax -S</span><br><span class="line">$ npm install node-tap -D</span><br></pre></td></tr></table></figure>
<h5 id="dependencies-依赖"><a href="#dependencies-依赖" class="headerlink" title="dependencies 依赖"></a>dependencies 依赖</h5><p>这个可以说是我们 npm 核心一项内容，依赖管理，这个对象里面的内容就是我们这个项目所依赖的 js 模块包。下面这段代码表示我们依赖了 <code>markdown-it</code> 这个包，版本是 <code>^8.1.0</code> ，代表最小依赖版本是 <code>8.1.0</code> ，如果这个包有更新，那么当我们使用 npm install 命令的时候，npm 会帮我们下载最新的包。当别人引用我们这个包的时候，包内的依赖包也会被下载下来。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"dependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"markdown-it"</span>: <span class="string">"^8.1.0"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="devDependencies-开发依赖"><a href="#devDependencies-开发依赖" class="headerlink" title="devDependencies 开发依赖"></a>devDependencies 开发依赖</h5><p>在我们开发的时候会用到的一些包，只是在开发环境中需要用到，但是在别人引用我们包的时候，不会用到这些内容，放在 devDependencies 的包，在别人引用的时候不会被 npm 下载。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"devDependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"autoprefixer"</span>: <span class="string">"^6.4.0"</span>,<span class="number">0</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>babel-preset-es2015<span class="string">": "</span>^<span class="number">6.0</span><span class="number">.0</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>babel-preset-stage<span class="number">-2</span><span class="string">": "</span>^<span class="number">6.0</span><span class="number">.0</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>babel-register<span class="string">": "</span>^<span class="number">6.0</span><span class="number">.0</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>webpack<span class="string">": "</span>^<span class="number">1.13</span><span class="number">.2</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>webpack-dev-middleware<span class="string">": "</span>^<span class="number">1.8</span><span class="number">.3</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>webpack-hot-middleware<span class="string">": "</span>^<span class="number">2.12</span><span class="number">.2</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>webpack-merge<span class="string">": "</span>^<span class="number">0.14</span><span class="number">.1</span><span class="string">",</span></span><br><span class="line"><span class="string">    "</span>highlightjs<span class="string">": "</span>^<span class="number">9.8</span><span class="number">.0</span><span class="string">"</span></span><br><span class="line"><span class="string">&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>当你有了一个完整的 package.json 文件的时候，就可以让人一眼看出来，这个模块的基本信息，和这个模块所需要依赖的包。我们可以通过 npm install 就可以很方便的下载好这个模块所需要的包。</p>
<p>npm install 默认会安装 dependencies 字段和 devDependencies 字段中的所有模块，如果使用 –production 参数，可以只安装 dependencies 字段的模块。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ npm install --production</span><br><span class="line"><span class="comment"># 或者</span></span><br><span class="line">$ NODE_ENV=production npm install</span><br></pre></td></tr></table></figure></p>
<p>一旦安装了某个模块，就可以在代码中用 require 命令加载这个模块。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> backbone = <span class="built_in">require</span>(<span class="string">'backbone'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(backbone.VERSION)</span><br></pre></td></tr></table></figure></p>
<h3 id="npm-run"><a href="#npm-run" class="headerlink" title="npm run"></a>npm run</h3><p>npm 不仅可以用于模块管理，还可以用于执行脚本。package.json 文件有一个 scripts 字段，可以用于指定脚本命令，供 npm 直接调用。<br>package.json<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"name"</span>: <span class="string">"myproject"</span>,</span><br><span class="line">  <span class="string">"devDependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"jshint"</span>: <span class="string">"latest"</span>,</span><br><span class="line">    <span class="string">"browserify"</span>: <span class="string">"latest"</span>,</span><br><span class="line">    <span class="string">"mocha"</span>: <span class="string">"latest"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"scripts"</span>: &#123;</span><br><span class="line">    <span class="string">"lint"</span>: <span class="string">"jshint **.js"</span>,</span><br><span class="line">    <span class="string">"test"</span>: <span class="string">"mocha test/"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="scripts-脚本"><a href="#scripts-脚本" class="headerlink" title="scripts 脚本"></a>scripts 脚本</h4><p>顾名思义，就是一些脚本代码，可以通过 <code>npm run script-key</code> 来调用，例如在这个 package.json 的文件夹下使用 <code>npm run dev</code> 就相当于运行了 <code>node build/dev-server.js</code> 这一段代码。使用 scripts 的目的就是为了把一些要执行的代码合并到一起，使用 npm run 来快速的运行，方便省事。<br>npm run 是 npm run-script 的缩写，一般都使用前者，但是后者可以更好的反应这个命令的本质。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 脚本</span></span><br><span class="line"><span class="string">"scripts"</span>: &#123;</span><br><span class="line">    <span class="string">"dev"</span>: <span class="string">"node build/dev-server.js"</span>,</span><br><span class="line">    <span class="string">"build"</span>: <span class="string">"node build/build.js"</span>,</span><br><span class="line">    <span class="string">"docs"</span>: <span class="string">"node build/docs.js"</span>,</span><br><span class="line">    <span class="string">"build-docs"</span>: <span class="string">"npm run docs &amp; git checkout gh-pages &amp; xcopy /sy dist\\* . &amp; git add . &amp; git commit -m 'auto-pages' &amp; git push &amp; git checkout master"</span>,</span><br><span class="line">    <span class="string">"build-publish"</span>: <span class="string">"rmdir /S /Q lib &amp; npm run build &amp;git add . &amp; git commit -m auto-build &amp; npm version patch &amp; npm publish &amp; git push"</span>,</span><br><span class="line">    <span class="string">"lint"</span>: <span class="string">"eslint --ext .js,.vue src"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>npm run 如果不加任何参数，直接运行，会列出 package.json 里面所有可以执行的脚本命令。<br>npm 内置了两个命令简写， npm test 等同于执行 npm run test，npm start 等同于执行 npm run start。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"build"</span>: <span class="string">"npm run build-js &amp;&amp; npm run build-css"</span></span><br></pre></td></tr></table></figure>
<p>上面的写法是先运行 npm run build-js ，然后再运行 npm run build-css ，两个命令中间用 &amp;&amp; 连接。如果希望两个命令同时平行执行，它们中间可以用 &amp; 连接。</p>
<p>写在 scripts 属性中的命令，也可以在 node_modules/.bin 目录中直接写成 bash 脚本。下面是一个 bash 脚本。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> site/main</span><br><span class="line">browserify browser/main.js | uglifyjs -mc &gt; static/bundle.js</span><br></pre></td></tr></table></figure></p>
<p>假定上面的脚本文件名为 build.sh ，并且权限为可执行，就可以在 scripts 属性中引用该文件。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"build-js"</span>: <span class="string">"bin/build.sh"</span></span><br></pre></td></tr></table></figure></p>
<h3 id="pre-和-post-脚本"><a href="#pre-和-post-脚本" class="headerlink" title="pre- 和 post- 脚本"></a>pre- 和 post- 脚本</h3><p>npm run 为每条命令提供了 pre- 和 post- 两个钩子（hook）。以 npm run lint 为例，执行这条命令之前，npm 会先查看有没有定义 prelint 和 postlint 两个钩子，如果有的话，就会先执行 npm run prelint，然后执行 npm run lint，最后执行 npm run postlint。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"name"</span>: <span class="string">"myproject"</span>,</span><br><span class="line">  <span class="string">"devDependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"eslint"</span>: <span class="string">"latest"</span></span><br><span class="line">    <span class="string">"karma"</span>: <span class="string">"latest"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"scripts"</span>: &#123;</span><br><span class="line">    <span class="string">"lint"</span>: <span class="string">"eslint --cache --ext .js --ext .jsx src"</span>,</span><br><span class="line">    <span class="string">"test"</span>: <span class="string">"karma start --log-leve=error karma.config.js --single-run=true"</span>,</span><br><span class="line">    <span class="string">"pretest"</span>: <span class="string">"npm run lint"</span>,</span><br><span class="line">    <span class="string">"posttest"</span>: <span class="string">"echo 'Finished running tests'"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码是一个 package.json 文件的例子。如果执行 npm test，会按下面的顺序执行相应的命令。</p>
<ol>
<li>pretest</li>
<li>test</li>
<li>posttest</li>
</ol>
<p>如果执行过程出错，就不会执行排在后面的脚本，即如果 prelint 脚本执行出错，就不会接着执行 lint 和 postlint 脚本。</p>
<h3 id="npm-bin"><a href="#npm-bin" class="headerlink" title="npm bin"></a>npm bin</h3><p>npm bin 命令显示相对于当前目录的，Node 模块的可执行脚本所在的目录（即 .bin 目录）。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 项目根目录下执行</span></span><br><span class="line">$ npm bin</span><br><span class="line">./node_modules/.bin</span><br></pre></td></tr></table></figure></p>
<h1 id="创建全局链接"><a href="#创建全局链接" class="headerlink" title="创建全局链接"></a>创建全局链接</h1><p>npm 提供了一个有趣的命令 npm link，它的功能是在本地包和全局包之间创建符号链接。我们说过使用全局模式安装的包不能直接通过 require 使用。但通过 npm link 命令可以打破这一限制。举个例子，我们已经通过 <code>npm install -g express</code> 安装了 express，这时在工程的目录下运行命令：<br><code>npm link express ./node_modules/express -&gt; /user/local/lib/node_modules/express</code><br>我们可以在 node_modules 子目录中发现一个指向安装到全局的包的符号链接。通过这种方法，我们就可以把全局包当做本地包来使用了。<br>除了将全局的包链接到本地以外，使用 npm link 命令还可以将本地的包链接到全局。使用方法是在包目录（package.json 所在目录）中运行 npm link 命令。如果我们要开发一个包，利用这种方法可以非常方便地在不同的工程间进行测试。</p>
<h1 id="创建包"><a href="#创建包" class="headerlink" title="创建包"></a>创建包</h1><p>包是在模块基础上更深一步的抽象，Node.js 的包类似于 C/C++ 的函数库或者 Java、.Net 的类库。它将某个独立的功能封装起来，用于发布、更新、依赖管理和版本控制。Node.js 根据 CommonJS 规范实现了包机制，开发了 npm 来解决包的发布和获取需求。<br>Node.js 的包是一个目录，其中包含了一个 JSON 格式的包说明文件 package.json。严格符合 CommonJS 规范的包应该具备以下特征：<br>。package.json 必须在包的顶层目录下；<br>。二进制文件应该在 bin 目录下；<br>。JavaScript 代码应该在 lib 目录下；<br>。文档应该在 doc 目录下；<br>。单元测试应该在 test 目录下。</p>
<p>Node.js 对包的要求并没有这么严格，只要顶层目录下有 package.json，并符合一些规范即可。当然为了提高兼容性，我们还是建议你在制作包的时候，严格遵守 CommonJS 规范。</p>
<p>我们也可以把文件夹封装为一个模块，即所谓的包。包通常是一些模块的集合，在模块的基础上提供了更高层的抽象，相当于提供了一些固定接口的函数库。通过定制 package.json，我们可以创建更复杂，更完善，更符合规范的包用于发布。</p>
<p>Node.js 在调用某个包时，会首先检查包中 packgage.json 文件的 main 字段，将其作为包的接口模块，如果 package.json 或 main 字段不存在，会尝试寻找 index.js 或 index.node 作为包的接口。</p>
<p>package.json 是 CommonJS 规定的用来描述包的文件，完全符合规范的 package.json 文件应该含有以下字段：<br><span id="inline-yellow">name</span>: 包的名字，必须是唯一的，由小写英文字母、数字和下划线组成，不能包含空格。<br><span id="inline-blue">description</span>: 包的简要说明。<br><span id="inline-green">version</span>: 符合语义化版本识别规范的版本字符串。<br><span id="inline-red">keywords</span>: 关键字数组，通常用于搜索。<br><span id="inline-purple">maintainers</span>: 维护者数组，每个元素要包含 name 、email(可选)、web(可选)字段。<br><span id="inline-yellow">contributors</span>: 贡献者数组，格式与 maintainers 相同。包的作者应该是贡献者数组的第一个元素。<br><span id="inline-blue">bugs</span>: 提交 bug 的地址，可以是网址或者电子邮件地址。<br><span id="inline-green">licenses</span>: 许可证数组，每个元素要包含 type（许可证的名称）和 url（链接到许可证文本的地址）字段。<br><span id="inline-red">repositories</span>: 仓库托管地址数组，每个元素要包含 type（仓库的类型，如 git）、URL（仓库的地址）和 path（相对于仓库的路径，可选）字段。<br><span id="inline-purple">dependencies</span>: 包的依赖，一个关联数组，由包名称和版本号组成。</p>
<h1 id="包的发布"><a href="#包的发布" class="headerlink" title="包的发布"></a>包的发布</h1><p>通过使用 npm init 可以根据交互式回答产生一个符合标准的 package.json。创建一个 index.js 作为包的接口,一个简单的包就制作完成了。<br>在发布前,我们还需要获得一个账号用于今后维护自己的包,使用 npm adduser 根据提示完成账号的创建<br>完成后可以使用 npm whoami 检测是否已经取得了账号。<br>接下来,在 package.json 所在目录下运行 npm publish，稍等片刻就可以完成发布了，打开浏览器，访问 <a href="http://search.npmjs.org/" target="_blank" rel="external">http://search.npmjs.org/</a> 就可以找到自己刚刚发布的包了。现在我们可以在世界的任意一台计算机上使用 npm install neveryumodule 命令来安装它。<br>如果你的包将来有更新,只需要在 package.json 文件中修改 version 字段,然后重新使用 npm publish 命令就行了。<br>如果你对已发布的包不满意，可以使用 npm unpublish 命令来取消发布。</p>
<p id="div-border-top-yellow"><em>需要说明的是：json 文件不能有注释</em><br></p>

<h1 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h1><p><a href="http://javascript.ruanyifeng.com/nodejs/npm.html" target="_blank" rel="external">http://javascript.ruanyifeng.com/nodejs/npm.html</a></p>
<h1 id="常用命令"><a href="#常用命令" class="headerlink" title="常用命令"></a>常用命令</h1><p>npm version  查看npm和node的版本<br>npm list –depth=0 [-g]  查看[全局]安装的包<br>npm root [-g]  查看[全局的]包的安装路径</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

<blockquote class="blockquote-center" style="color: #ccc;">
    -------------本文结束 <i class="fa fa-apple"></i> 感谢您的阅读-------------
</blockquote>

  <span id="inline-green" style="border-radius:3px;">作者</span>：<a class="link-blue" href="https://github.com/Neveryu" target="_blank">Neveryu</a><br/>有问题请 <a class="link-blue" href="https://neveryu.github.io/guestbook" target="_blank">留言</a> 或者私信我的 <a class="link-blue" href="http://weibo.com/Neveryu" target="_blank">微博</a>。

  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>满分是10分的话，这篇文章你给几分</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/reward/reward_wechat.png" alt="Never_yu WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/reward/reward_alipay.png" alt="Never_yu Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/npm/" rel="tag"><i class="fa fa-tag"></i> npm</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/20/amd-cmd/" rel="next" title="AMD，CMD 规范详解">
                <i class="fa fa-chevron-left"></i> AMD，CMD 规范详解
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/05/01/gulp/" rel="prev" title="gulp 详解与使用">
                gulp 详解与使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/avatar/avatar.png"
               alt="Never_yu" />
          <p class="site-author-name" itemprop="name">Never_yu</p>
          <p class="site-description motion-element" itemprop="description">Stay Hungry,Stay Foolish</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">36</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Neveryu" target="_blank" title="Github">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  Github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/Neveryu" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://codeigniter.org.cn/" title="CodeIgniter中国" target="_blank">CodeIgniter中国</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="/weblog" title="建站日志" target="_blank">建站日志</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/csdn_yudong" title="CSDN" target="_blank">CSDN</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://neveryu.github.io/neveryu" title="个人首页" target="_blank">个人首页</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="/reward" title="打赏" target="_blank">打赏</a>
                </li>
              
            </ul>
          </div>
        
      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#什么是-NPM"><span class="nav-number">1.</span> <span class="nav-text">什么是 NPM</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#为什么要使用-NPM"><span class="nav-number">2.</span> <span class="nav-text">为什么要使用 NPM</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#如何使用-NPM"><span class="nav-number">3.</span> <span class="nav-text">如何使用 NPM</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">3.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用"><span class="nav-number">3.2.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-init"><span class="nav-number">3.2.1.</span> <span class="nav-text">npm init</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-set"><span class="nav-number">3.2.2.</span> <span class="nav-text">npm set</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-info"><span class="nav-number">3.2.3.</span> <span class="nav-text">npm info</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-search"><span class="nav-number">3.2.4.</span> <span class="nav-text">npm search</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-list"><span class="nav-number">3.2.5.</span> <span class="nav-text">npm list</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-install"><span class="nav-number">3.2.6.</span> <span class="nav-text">npm install</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#本地模式和全局模式"><span class="nav-number">3.2.6.1.</span> <span class="nav-text">本地模式和全局模式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#安装不同版本"><span class="nav-number">3.2.6.2.</span> <span class="nav-text">安装不同版本</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#dependencies-依赖"><span class="nav-number">3.2.6.2.1.</span> <span class="nav-text">dependencies 依赖</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#devDependencies-开发依赖"><span class="nav-number">3.2.6.2.2.</span> <span class="nav-text">devDependencies 开发依赖</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-run"><span class="nav-number">3.2.7.</span> <span class="nav-text">npm run</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#scripts-脚本"><span class="nav-number">3.2.7.1.</span> <span class="nav-text">scripts 脚本</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pre-和-post-脚本"><span class="nav-number">3.2.8.</span> <span class="nav-text">pre- 和 post- 脚本</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#npm-bin"><span class="nav-number">3.2.9.</span> <span class="nav-text">npm bin</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建全局链接"><span class="nav-number">4.</span> <span class="nav-text">创建全局链接</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建包"><span class="nav-number">5.</span> <span class="nav-text">创建包</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#包的发布"><span class="nav-number">6.</span> <span class="nav-text">包的发布</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考链接"><span class="nav-number">7.</span> <span class="nav-text">参考链接</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常用命令"><span class="nav-number">8.</span> <span class="nav-text">常用命令</span></a></li></ol></div>
            
          </div>
        </section>
      

      
        <section style="border-top:1px dotted #ccc; padding-top:10px;">
          <iframe width="100%" height="120" class="share_self"  frameborder="0" scrolling="no" src="https://widget.weibo.com/weiboshow/index.php?language=&width=0&height=120&fansRow=2&ptype=1&speed=0&skin=5&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=5346488237&verifier=d529ff3a&dpc=1"></iframe>
        </section>
      
    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        

<div class="busuanzi-count">

  <!-- <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script> -->
  <!-- 上面这个是之前的，不知道为什么失效了，改成下面这个 -->
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">您是第<span class="busuanzi-value" id="busuanzi_value_site_uv"></span>个小伙伴</span>
  

  
    <span class="site-pv">本站总浏览<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>次</span>
  
  
</div>



        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Never_yu</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Pisces
  </a>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count" style="color: #e90f92;">全站共 156k 字</span>
</div>
        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


  <!-- 按需加载背景 -->
  <!-- 背景动画 -->
<script type="text/javascript">
  // 按需加载背景
  // 如果是all，就直接加载了
  if("pc" == "all") {
    $.getScript("/js/src/particle.js?v=5.0.1");
  }
  // 识别手机或电脑的js开始
  (function(){
    var res = GetRequest();
    var par = res['index'];
    if(par!='gfan'){
      var ua=navigator.userAgent.toLowerCase();
      var contains=function (a, b){
          if(a.indexOf(b)!=-1){return true;}
      };
      if((contains(ua,"android") && contains(ua,"mobile"))||(contains(ua,"android") && contains(ua,"mozilla"))||(contains(ua,"android") && contains(ua,"opera"))||contains(ua,"ucweb7")||contains(ua,"iphone")){
        return false;
      } else {
        $.getScript("/js/src/particle.js?v=5.0.1");
      }
    }
  })();
  function GetRequest() {
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
      }
    }
    return theRequest;
  }
</script>
<!-- 识别手机或电脑的js结束 -->  

  <!-- 页面点击小红心 -->
  <!-- 页面点击小红心 -->

  <script type="text/javascript" src="/js/src/love.js?v=5.0.1"></script>


  <!-- 鼠标移动，效果 -->
  <!-- 鼠标移动特效 -->

  <script type="text/javascript" src="/js/src/jquery-stars.js?v=5.0.1"></script>
  <script type="text/javascript">
  jQuery('body').jstars({
  	image_path: '/images',
  	image: 'candy-cane-stars.png',
  	style: 'white',
  	width: 34,
  	height: 34,
  	delay: 700,
  	frequency: 5
  });
  </script>


  <!-- 页面 title 进入/离开 效果 -->

  <script type="text/javascript">var OriginTitile=document.title,st;document.addEventListener("visibilitychange",function(){document.hidden?(document.title="≡[。。]≡ 回不去了吗？!",clearTimeout(st)):(document.title="(ฅ>ω<*ฅ) Thank Vue~ "+OriginTitile,st=setTimeout(function(){document.title=OriginTitile},4e3))})</script>


</body>
</html>
